package com.example.chatrecommendation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.chatrecommendation.bean.ChattingRecords;
import com.example.chatrecommendation.bean.dto.ChattingAddDto;
import com.example.chatrecommendation.bean.dto.Messages;
import com.example.chatrecommendation.bean.vo.ChattingListVo;
import com.example.chatrecommendation.mapper.ChattingRecordsMapper;
import com.example.chatrecommendation.service.ChattingRecordsService;
import com.example.chatrecommendation.tool.Api;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jasmine-drs
 * @description 针对表【chatting_records(聊天历史记录)】的数据库操作Service实现
 * @Date 2024-05-21 20:35:02
 */
@Service
@Slf4j
public class ChattingRecordsServiceImpl extends ServiceImpl<ChattingRecordsMapper, ChattingRecords> implements ChattingRecordsService {

	private final ChattingRecordsMapper chattingRecordsMapper;
	private final Api API;

	public ChattingRecordsServiceImpl(ChattingRecordsMapper chattingRecordsMapper, Api api) {
		this.chattingRecordsMapper = chattingRecordsMapper;
		API = api;
	}

	@Override
	public List<ChattingListVo> getChatRecords(Integer studentAccount, Integer type) {
		LambdaQueryWrapper<ChattingRecords> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ChattingRecords::getStudentAccount, studentAccount)
				.eq(ChattingRecords::getType, type)
				.orderByDesc(ChattingRecords::getCreateTime);
		List<ChattingRecords> chattingRecords = chattingRecordsMapper.selectList(wrapper);
		List<ChattingListVo> chattingListVos = new ArrayList<>();
		if (chattingRecords != null) {
			chattingRecords.forEach(chattingRecords1 ->
					chattingListVos.add(ChattingListVo.toChattingListVo(chattingRecords1)));
		}
		return chattingListVos;
	}

	@Override
	public void saveChatRecords(Integer id, List<Messages> list) {
		LambdaQueryWrapper<ChattingRecords> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ChattingRecords::getId, id);
//		先查找id，然后解析里面的聊天记录，再加上新的聊天记录
		ChattingRecords one = chattingRecordsMapper.selectOne(wrapper);
		if (one == null){
			throw new RuntimeException("聊天记录不存在");
		}
		String oneMessage = one.getMessage();
//		数据库里旧的历史记录
		List<Messages> odl = new ArrayList<>();
		//		解析message
		if (oneMessage == null) {
			oneMessage = "[]";
		}
		JSONArray messagesArray = new JSONArray(oneMessage);
		for (int i = 0; i < messagesArray.length(); i++) {
			JSONObject messageObject = messagesArray.getJSONObject(i);
			String role = messageObject.getString("role");
			String content = messageObject.getString("content");
			odl.add(new Messages(role, content));
		}
		odl.addAll(list);
		ChattingRecords records = new ChattingRecords();
		records.setMessage(odl.toString());
		int update = chattingRecordsMapper.update(records, wrapper);
		if (update != 1) {
			throw new RuntimeException("聊天记录保存失败");
		}
	}

	@Override
	public ChattingRecords addChatRecords(ChattingAddDto chattingAddDto) throws MalformedURLException {
//		构造chattingRecords
		ChattingRecords chattingRecords = new ChattingRecords();
		chattingRecords.setStudentAccount(chattingAddDto.getStudentAccount());
		String name = API.getChatRecordsName(chattingAddDto.getMessage());
		name = name.replace("\\\"", "");
		chattingRecords.setName(name);
//		chattingRecords.setMessage(chattingAddDto.getMessage().toString());
		chattingRecords.setType(chattingAddDto.getType());
//		设置创建时间为当前时间
		LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String formattedNow = now.format(formatter);
		log.info("当前时间：" + formattedNow);
		chattingRecords.setCreateTime(now);
//		插入chattingRecords
		chattingRecordsMapper.insert(chattingRecords);
		LambdaQueryWrapper<ChattingRecords> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ChattingRecords::getCreateTime, formattedNow);
//		查找chattingRecords
		return chattingRecordsMapper.selectOne(wrapper);
	}
}




